package edu.uoc.tdp.client.estudiants;

import edu.uoc.tdp.beans.conexio.Estudiant;
import edu.uoc.tdp.beans.proves.Prova;
import edu.uoc.tdp.common.EOlympicsException;
import edu.uoc.tdp.common.RemotEstudiantsInterface;
import edu.uoc.tdp.common.TDSLanguageUtils;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.GroupLayout;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;

/**
 * Pantalla que mostra el resultat de les proves realitzades pels estudiants
 * @author Jordi
 */
public class PantallaResultatProves extends javax.swing.JFrame {

    private RemotEstudiantsInterface remot;
    private Estudiant estudiant;
    List<Prova> entrada = new ArrayList<Prova>();
    List<Prova> proves_pendents = new ArrayList<Prova>();
    List<Integer> respostes = new ArrayList<Integer>();
    private int encerts;
    
    private GroupLayout disposicioPreguntes;
    private GroupLayout.ParallelGroup HoritzontalParalelPrincipal;
    private GroupLayout.SequentialGroup HoritzontalSequencialPrincipal ;
    private GroupLayout.ParallelGroup HoritzontalParalelSecundari ;
    private GroupLayout.ParallelGroup VerticalParalelPrincipal;
    private GroupLayout.SequentialGroup VerticalSequencialPrincipal ;


    /**
     * Constructor amb dos paràmetres   
     * @param pEstudiant           Identificador de l'estudiant actual
     * @param pRemot               Remot que ens permet connectar amb el servidor
     */
    public PantallaResultatProves(Estudiant pEstudiant, RemotEstudiantsInterface pRemot) {
        estudiant = pEstudiant;
        remot = pRemot;

        initComponents();
        carregainicial();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {

            public void windowClosing(java.awt.event.WindowEvent evt) {
                tancarFinestra(evt);
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jPanel1 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jTable1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jTable1PropertyChange(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 598, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jLabel1.setFont(new java.awt.Font("Arial", 0, 14));
        jLabel1.setForeground(new java.awt.Color(0, 0, 255));
        jLabel1.setText("Llistat de Proves Realitzades");

        jLabel2.setFont(new java.awt.Font("Arial", 0, 14));
        jLabel2.setForeground(new java.awt.Color(0, 0, 255));
        jLabel2.setText("Resultat:");

        jButton3.setText("Tornar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel1.setAutoscrolls(true);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 618, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 255, Short.MAX_VALUE)
        );

        jScrollPane2.setViewportView(jPanel1);
        jPanel1.getAccessibleContext().setAccessibleName("");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jButton3)
                        .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap(19, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3)
                .addGap(22, 22, 22))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
     /**
     * Tanca la finestra
     * @param evt               disparador
     */
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    tancarFinestraboto(evt);
}//GEN-LAST:event_jButton3ActionPerformed

private void jTable1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jTable1PropertyChange

}//GEN-LAST:event_jTable1PropertyChange
     /**
     *Mostra el resultat de la prova seleccionada
     * @param evt               disparador
     */ 
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        
        Prova auxprova = new Prova();
        auxprova = proves_pendents.get(jTable1.getSelectedRow());
        int numpreguntes = 0;
                
        jPanel1.removeAll();
        disposicioPreguntes = new GroupLayout(jPanel1);
        jPanel1.setLayout(disposicioPreguntes);
               
        HoritzontalParalelPrincipal= disposicioPreguntes.createParallelGroup(GroupLayout.Alignment.LEADING);
        HoritzontalSequencialPrincipal=disposicioPreguntes.createSequentialGroup().addGap(25, 25, 25);
        HoritzontalParalelPrincipal.addGroup(HoritzontalSequencialPrincipal);
        HoritzontalParalelSecundari=disposicioPreguntes.createParallelGroup(GroupLayout.Alignment.LEADING);
        HoritzontalSequencialPrincipal.addGroup(HoritzontalParalelSecundari);        
        disposicioPreguntes.setHorizontalGroup(HoritzontalParalelPrincipal);
        
        VerticalParalelPrincipal= disposicioPreguntes.createParallelGroup(GroupLayout.Alignment.LEADING);
        VerticalSequencialPrincipal=disposicioPreguntes.createSequentialGroup().addGap(25, 25, 25);
        VerticalParalelPrincipal.addGroup(VerticalSequencialPrincipal);

        disposicioPreguntes.setVerticalGroup(VerticalParalelPrincipal); 
        
        String tipusronda = tipusderonda(auxprova);
        
        if (tipusronda.equals("F")){
            numpreguntes = auxprova.getRondaFinal().getNombrePreguntes();
        } else if (tipusronda.equals("E")){
            numpreguntes = auxprova.getRondaEliminatoria().getNombrePreguntes();
          }
        
        encerts = 0;
        
        for (int i=0; i < numpreguntes; i++){
            try {
                String respostaestudiant = remot.RespostaPregunta(auxprova.getIdProva(), tipusronda, estudiant.getIdIntern(), i+1);
                String respostacorrecta = remot.RespostaCorrecta(auxprova.getIdProva(), tipusronda, i+1);
                carregarPregunta(i,respostaestudiant,respostacorrecta);
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog 
                  (null, ex.getMessage(), TDSLanguageUtils.getMessage("estudiants.common.error.literalerror"), JOptionPane.ERROR_MESSAGE);
            } catch (RemoteException ex) {
                JOptionPane.showMessageDialog 
                  (null,TDSLanguageUtils.getMessage("estudiants.common.error.conexio.miss"),
                   TDSLanguageUtils.getMessage("estudiants.common.error.literalerror"), JOptionPane.ERROR_MESSAGE);
            } catch (EOlympicsException ex) {
                JOptionPane.showMessageDialog 
                  (null, ex.getMessage(), TDSLanguageUtils.getMessage("estudiants.common.error.literalerror"), JOptionPane.ERROR_MESSAGE);
            }
        }
        
        jLabel2.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.historic.prova.title") 
                        + auxprova.getDescripcio() + ": " + encerts + " " 
                        + TDSLanguageUtils.getMessage("estudiants.pantalla.historic.prova.title2"));
}//GEN-LAST:event_jTable1MouseClicked
     /**
     * Fa la primera carrega de la pantalla. Posant el valor a els elements de texte i fent la carrega
     * de les proves realitzades
     */
    private void carregainicial() {
        try {
            
            TDSLanguageUtils.setDefaultLanguage("edu/uoc/tdp/i18n/messages");
            this.setTitle(TDSLanguageUtils.getMessage("estudiants.pantalla.historic.nom"));
            java.util.Date hoy = new Date(); //Fecha de hoy
            final long MILLSECS_PER_DAY = 24 * 60 * 60 * 1000; //Milisegundos al día
            jLabel1.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.historic.llistaproves"));
            jButton3.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.historic.Button.tornar"));
            Prova table_prova = new Prova();

            entrada = new ArrayList<Prova>();
            proves_pendents = new ArrayList<Prova>();
            
            entrada = remot.ProvesFinalitzades(estudiant.getIdIntern());

            DefaultTableModel modelo = new DefaultTableModel()
            {
                @Override
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;
                }
            };            

            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.historic.table.col1"));
            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.historic.table.col2"));
            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.historic.table.col3"));
            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.historic.table.col4"));
            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.historic.table.col5"));

            for (int i = 0; i < entrada.size(); i++) {
                table_prova = entrada.get(i);
                String tipusronda = tipusderonda(table_prova);
                int dies = 0;

                if (remot.ComprovaParticipacio(table_prova.getIdProva(), tipusronda, estudiant.getIdIntern()) &&
                    remot.ComprovaRealitzacio(table_prova.getIdProva(), tipusronda, estudiant.getIdIntern())) {
                    Object[] fila = new Object[5];
                    fila[0] = table_prova.getDescripcio();
                    if (tipusronda.equals("F")) {
                        fila[1] = table_prova.getRondaFinal().getNombrePreguntes();
                        fila[2] = table_prova.getRondaFinal().getDataIniRealitzacio();
                        fila[3] = table_prova.getRondaFinal().getDataFiRealitzacio();
                        dies = (int) ((table_prova.getRondaFinal().getDataFiRealitzacio().getTime() - hoy.getTime()) / MILLSECS_PER_DAY);
                        fila[4] = dies;
                    } else {
                        fila[1] = table_prova.getRondaEliminatoria().getNombrePreguntes();
                        fila[2] = table_prova.getRondaEliminatoria().getDataIniRealitzacio();
                        fila[3] = table_prova.getRondaEliminatoria().getDataFiRealitzacio();
                        dies = (int) ((table_prova.getRondaEliminatoria().getDataFiRealitzacio().getTime() - hoy.getTime()) / MILLSECS_PER_DAY);
                        fila[4] = dies;
                      }
                    proves_pendents.add(table_prova);
                    modelo.addRow(fila);
                }
            }
            this.jTable1.setModel(modelo);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

     /**
     * Dibuixa una pregunta a la pantalla i assigna el valor al vector repostes en funcio
     * del checkbox triat
     * @param integer               numero de pregunta a carregar
     * @param String                Resposta entrada per l'estudiant
     * @param String                Resposta correcta
     */     
     private void carregarPregunta(int i,String respostaestudiant,String respostacorrecta){
        
        JLabel lPregunta= new JLabel();
        JRadioButton jButtonA= new JRadioButton();
        JRadioButton jButtonB= new JRadioButton();
        JRadioButton jButtonC= new JRadioButton();
        JRadioButton jButtonD= new JRadioButton();
        JCheckBox jCheckResultat = new JCheckBox();

        int contadorLabel = i + 1;
        
        lPregunta.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.realitzacio.question") + contadorLabel);
        lPregunta.setVisible(true);
        jButtonA.setVisible(true); 
        jButtonB.setVisible(true); 
        jButtonC.setVisible(true); 
        jButtonD.setVisible(true); 
        jCheckResultat.setVisible(true); 
        
        jButtonA.setText("A"); 
        jButtonB.setText("B"); 
        jButtonC.setText("C");  
        jButtonD.setText("D"); 
        jCheckResultat.setText("Resposta: " + respostacorrecta);            
        
        if (respostaestudiant.equals("A")){
                jButtonA.setSelected(true);
        } else if(respostaestudiant.equals("B")){
                    jButtonB.setSelected(true);
               } else if (respostaestudiant.equals("C")){
                            jButtonC.setSelected(true);
                      } else if (respostaestudiant.equals("D")){
                            jButtonD.setSelected(true);
                             }
        
        if ((respostacorrecta.equals(respostaestudiant))){
                jCheckResultat.setSelected(true);
                encerts++;
        }
        
        
        lPregunta.setHorizontalAlignment(SwingConstants.LEFT);
        jButtonA.setHorizontalAlignment(SwingConstants.LEFT);
        jButtonB.setHorizontalAlignment(SwingConstants.LEFT);
        jButtonC.setHorizontalAlignment(SwingConstants.LEFT);
        jButtonD.setHorizontalAlignment(SwingConstants.LEFT);
        jCheckResultat.setHorizontalAlignment(SwingConstants.LEFT);
        
        jButtonA.setName("A" + i +"");
        jButtonB.setName("B" + i +"");
        jButtonC.setName("V" + i +"");
        jButtonD.setName("D" + i +"");
        jCheckResultat.setName("resultat" + i +"");
        
        jButtonA.setEnabled(false);
        jButtonB.setEnabled(false);
        jButtonC.setEnabled(false);
        jButtonD.setEnabled(false);
        jCheckResultat.setEnabled(false);
        
       //Per situar-lo en el panell 
              
        GroupLayout.SequentialGroup sequencial;
        GroupLayout.ParallelGroup paralel;
        sequencial=disposicioPreguntes.createSequentialGroup();        
        HoritzontalParalelSecundari.addGroup(sequencial); 
        paralel=disposicioPreguntes.createParallelGroup(GroupLayout.Alignment.BASELINE);        
        VerticalSequencialPrincipal.addGroup(paralel);
        
        sequencial.addComponent(lPregunta).addGap(100,100,100);
        sequencial.addComponent(jButtonA).addGap(25,25,25);
        sequencial.addComponent(jButtonB).addGap(25,25,25);
        sequencial.addComponent(jButtonC).addGap(25,25,25);
        sequencial.addComponent(jButtonD).addGap(25,25,25);
        sequencial.addComponent(jCheckResultat).addGap(25,25,25);
       
        paralel.addComponent(lPregunta);
        paralel.addComponent(jButtonA);
        paralel.addComponent(jButtonB);
        paralel.addComponent(jButtonC);
        paralel.addComponent(jButtonD);
        paralel.addComponent(jCheckResultat);           
      
    }  

     /**
     * Retorna el tipus de ronda de la prova
     * @param  Prova      Prova
     * @return String     Tipus de ronda
     */  
    private String tipusderonda(Prova prova) {

        String sortida = "";

        if (prova.getIdEstat() == 3 || prova.getIdEstat() == 4) {
            sortida = "E";
        } else if (prova.getIdEstat() == 5 || prova.getIdEstat() == 6) {
            sortida = "F";
        } else {
            sortida = "";
        }
        return sortida;
    }

     /**
     * Tancament de la finestra des de d'un windowevent
     * @param evt               disparador
     */
    private void tancarFinestra(java.awt.event.WindowEvent evt) {
        dispose();
        System.exit(0);
    }
     /**
     * Tancament de la finestra des des del boto tancar
     * @param evt               disparador
     */ 
    private void tancarFinestraboto(java.awt.event.ActionEvent evt) {
        dispose();
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
